package org.dromara.system.controller.common;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import org.dromara.system.config.ServerConfig;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.utils.file.FileUploadUtils;
import org.dromara.system.domain.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/app/common")
@RequiredArgsConstructor
public class CommonController {


    private final ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @SaIgnore
    @PostMapping("/upload")
    public R<?> uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = Constants.UPLOAD + "/upload";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String, Object> ajax = new HashMap<>();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            return R.ok(ajax);
        } catch (Exception e) {
            System.out.println("上传文件异常:" + e.getMessage());
            return R.fail(e.getMessage());
        }
    }
}
